#! /usr/bin/python3
# -*- coding: UTF-8 -*-

if __name__ == "__main__":
	raise Exception("不支持从这里调用")

__version__ = "1.0"
__all__ = []

from uuid import uuid4

from com.mousechsh.business.lib.model.MouseChshAppModel import MouseChshAppModel
from com.mousechsh.business.lib.MouseChshAuthorizationAnnotition import MouseChshRemoteAuthorizationAnnotition
from com.mousechsh.business.lib.model.MouseChshDomainModel import MouseChshDomainModel
from com.mousechsh.business.lib.model.MouseChshKeyValueModel import MouseChshKeyValueModel
from com.mousechsh.common.data.MouseChshDao import MouseChshDao
from com.mousechsh.common.data.MouseChshData import mousechsh_data_merge
from com.mousechsh.common.data.json.MouseChshJson import mousechsh_json_to_json
from com.mousechsh.common.io.db.MouseChshPostgresql import MouseChshPostgresql
from com.mousechsh.common.middle.http.MouseChshHttpHeader import mousechsh_http_header_accept_language_annotation
from com.mousechsh.common.middle.rest_api.MouseChshRestApi import mousechsh_rest_api_annotation
from com.mousechsh.common.middle.router.MouseChshCorsAnnotition import mousechsh_cors_annotation
from com.mousechsh.common.middle.router.MouseChshHttpRouter import mousechsh_http_router_annotation
from com.mousechsh.common.util.MouseChshDateTime import MouseChshDateTime


@mousechsh_http_router_annotation(method=['POST', 'OPTIONS'], path='/app/add')
@mousechsh_cors_annotation()
@mousechsh_http_header_accept_language_annotation()
@MouseChshRemoteAuthorizationAnnotition()
@mousechsh_rest_api_annotation()
def _addApp(params):
	lang = params.get('lang', 'zh-cn')
	app = MouseChshAppModel()
	app.set_data(params)
	app.Id = str(uuid4()).upper()
	db = MouseChshPostgresql()
	db.connect()
	db.execute(
		'''
	   INSERT INTO "A_Application"."T_App"(
		   "C_Id",
		   "C_CrOn",
		   "C_MoOn",
		   "L_Scheme",
		   "X_Data",
		   "C_Name",
		   "L_Domain_Id",
		   "X_Display",
		   "L_AppType",
		   "L_Protocol",
		   "C_IpOrHost",
		   "C_Port",
		   "C_Path",
		   "C_Permission",
		   "L_Member_Id_Default"
	   ) VALUES (
		   %(id)s,
		   %(cron)s,
		   %(moon)s,
		   'App',
		   '{}',
		   %(name)s,
		   %(domain)s,
		   %(display)s,
		   %(type)s,
		   %(protocol)s,
		   %(host)s,
		   %(port)s,
		   %(path)s,
		   %(permission)s,
		   %(member)s
	   )
		   ''', {
			'id': app.get('Id'),
			'cron': MouseChshDateTime().to_timestamp(),
			'moon': MouseChshDateTime().to_timestamp(),
			'name': app.get('Name'),
			'domain': app.get('Domain'),
			'display': mousechsh_json_to_json(
				{
					lang: app.get('Display'),
					'': lang
				}
			),
			'type': app.get('Type'),
			'protocol': app.get('Protocol'),
			'host': app.get('Host'),
			'port': app.get('Port'),
			'path': app.get('Path'),
			'permission': app.get('Permission'),
			'member': app.get('Member'),
		}
	)
	db.commit()
	db.close()
	return app.get('Id')


@mousechsh_http_router_annotation(method=['POST', 'OPTIONS'], path='/app/remove')
@mousechsh_cors_annotation()
@mousechsh_http_header_accept_language_annotation()
@MouseChshRemoteAuthorizationAnnotition()
@mousechsh_rest_api_annotation()
def _removeApp(params):
	app = MouseChshAppModel()
	app.set_data(params)
	db = MouseChshPostgresql()
	db.connect()
	db.execute(
		'''
	   DELETE FROM "A_Application"."T_App"
	   WHERE "C_Id" = %(id)s
		   ''', {
			'id': app.get('Id')
		}
	)
	db.commit()
	db.close()
	return True


@mousechsh_http_router_annotation(method=['POST', 'OPTIONS'], path='/app/update')
@mousechsh_cors_annotation()
@mousechsh_http_header_accept_language_annotation()
@MouseChshRemoteAuthorizationAnnotition()
@mousechsh_rest_api_annotation()
def _updateApp(params):
	lang = params.get('lang', 'zh-cn')
	app = MouseChshAppModel()
	app.set_data(params)
	db = MouseChshPostgresql()
	db.connect()
	data = db.get(
		'''
	   SELECT
		   "C_Id",
		   "C_CrOn",
		   "C_CrBy",
		   "C_MoOn",
		   "C_MoBy",
		   "C_RvOn",
		   "C_RvBy",
		   "C_St",
		   "C_Owner",
		   "C_Flag",
		   "L_Scheme",
		   "X_Data",
		   "X_Property",
		   "C_Name",
		   "L_Domain_Id" AS "C_Domain_Id",
		   COALESCE( "X_Display" ->> %(lang)s, "X_Display" ->> ( "X_Display" ->> '' ) ) AS "C_Display",
		   "L_AppType" AS "C_AppType",
		   "L_Protocol" AS "C_Protocol",
		   "C_IpOrHost",
		   "C_Port",
		   "C_Path",
		   "C_Permission",
		   "L_Member_Id_Default" AS "C_Member_DefaultId"
	   FROM "A_Application"."T_App"
	   WHERE "C_Id" = %(id)s
		   ''', {
			'lang': lang,
			'id': app.get('Id')
		}
	)
	db.close()
	dao = MouseChshDao()
	dao.set_model(MouseChshAppModel)
	apps = dao.parse(data)
	if len(apps) <= 0:
		return
	app = mousechsh_data_merge(apps[0], app)
	db = MouseChshPostgresql()
	db.connect()
	db.execute(
		'''
	   UPDATE "A_Application"."T_App" SET
		   "C_MoOn"             = %(moon)s,
		   "L_Scheme"           = 'App',
		   "X_Data"             = '{}',
		   "C_Name"             = %(name)s,
		   "L_Domain_Id"        = %(domain)s,
		   "X_Display"          = "X_Display" || %(display)s,
		   "L_AppType"          = %(type)s,
		   "L_Protocol"         = %(protocol)s,
		   "C_IpOrHost"         = %(host)s,
		   "C_Port"             = %(port)s,
		   "C_Path"             = %(path)s,
		   "C_Permission"       = %(permission)s,
		   "L_Member_Id_Default" = %(member)s
	   WHERE "C_Id"             = %(id)s
		   ''', {
			'moon': MouseChshDateTime().to_timestamp(),
			'name': app.get('Name'),
			'domain': app.get('Domain'),
			'display': mousechsh_json_to_json(
				{
					lang: app.get('Display').get(lang, None) if isinstance(
						app.get('Display'), dict
					) else app.get('Display'),
					'': lang
				}
			),
			'type': app.get('Type'),
			'protocol': app.get('Protocol'),
			'host': app.get('Host'),
			'port': app.get('Port'),
			'path': app.get('Path'),
			'permission': (False if app.get('Permission') == 0 else True),
			'member': app.get('Member'),
			'id': app.get('Id')
		}
	)
	db.commit()
	db.close()
	return app.get('Id')


@mousechsh_http_router_annotation(method=['POST', 'OPTIONS'], path='/app/get')
@mousechsh_cors_annotation()
@mousechsh_http_header_accept_language_annotation()
@MouseChshRemoteAuthorizationAnnotition()
@mousechsh_rest_api_annotation()
def _getApp(params):
	lang = params.get('lang', 'zh-cn')
	app = MouseChshAppModel()
	app.set_data(params)
	db = MouseChshPostgresql()
	db.connect()
	data = db.get(
		'''
	   SELECT
		   A."C_Id",
		   A."C_CrOn",
		   A."C_CrBy",
		   A."C_MoOn",
		   A."C_MoBy",
		   A."C_RvOn",
		   A."C_RvBy",
		   A."C_St",
		   A."C_Owner",
		   A."C_Flag",
		   A."L_Scheme",
		   A."X_Data",
		   A."X_Property",
		   A."C_Name",
		   A."L_Domain_Id" AS "C_Domain_Id",
		   A."L_Domain_Id",
		   COALESCE( B."X_Display" ->> %(lang)s, B."X_Display" ->> ( B."X_Display" ->> '' ) ) AS "L_Domain_Display",
		   COALESCE( A."X_Display" ->> %(lang)s, A."X_Display" ->> ( A."X_Display" ->> '' ) ) AS "C_Display",
		   A."X_Display",
		   A."L_AppType" AS "C_AppType",
		   A."L_AppType" AS "L_AppType_Key",
		   COALESCE( C."X_Display" ->> %(lang)s, C."X_Display" ->> ( C."X_Display" ->> '' ) ) AS "L_AppType_Display",
		   A."L_Protocol" AS "C_Protocol",
		   A."L_Protocol" AS "L_Protocol_Key",
		   COALESCE( D."X_Display" ->> %(lang)s, D."X_Display" ->> ( D."X_Display" ->> '' ) ) AS "L_Protocol_Display",
		   A."C_IpOrHost",
		   A."C_Port",
		   A."C_Path",
		   A."C_Permission",
		   A."L_Member_Id_Default" AS "L_Member_DefaultId"
	   FROM "A_Application"."T_App" A
	   INNER JOIN "A_AD"."T_Domain" B
		   ON A."L_Domain_Id" = B."C_Id"
	   LEFT OUTER JOIN "A_Const"."W_KeyValue" C
		   ON A."L_AppType"   = C."C_Key"
	   LEFT OUTER JOIN "A_Const"."W_KeyValue" D
		   ON A."L_Protocol"  = D."C_Key"
	   ORDER BY A."C_Order" ASC
	   LIMIT 100
		   ''', {
			'lang': lang
		}
	)
	db.close()
	dao = MouseChshDao()
	dao.set_model(MouseChshAppModel)
	dao.set_extra_model(MouseChshDomainModel)
	dao.set_extra_model(MouseChshKeyValueModel, key='AppType')
	dao.set_extra_model(MouseChshKeyValueModel, key='Protocol')
	apps = dao.parse(data)
	return apps


@mousechsh_http_router_annotation(method=['POST', 'OPTIONS'], path='/app/one')
@mousechsh_cors_annotation()
@mousechsh_http_header_accept_language_annotation()
@MouseChshRemoteAuthorizationAnnotition()
@mousechsh_rest_api_annotation()
def _getOneApp(params):
	lang = params.get('lang', 'zh-cn')
	app = MouseChshAppModel()
	app.set_data(params)
	db = MouseChshPostgresql()
	db.connect()
	data = db.get(
		'''
	   SELECT
		   A."C_Id",
		   A."C_CrOn",
		   A."C_CrBy",
		   A."C_MoOn",
		   A."C_MoBy",
		   A."C_RvOn",
		   A."C_RvBy",
		   A."C_St",
		   A."C_Owner",
		   A."C_Flag",
		   A."L_Scheme",
		   A."X_Data",
		   A."X_Property",
		   A."C_Name",
		   A."L_Domain_Id" AS "C_Domain_Id",
		   A."L_Domain_Id",
		   COALESCE( B."X_Display" ->> %(lang)s, B."X_Display" ->> ( B."X_Display" ->> '' ) ) AS "L_Domain_Display",
		   COALESCE( A."X_Display" ->> %(lang)s, A."X_Display" ->> ( A."X_Display" ->> '' ) ) AS "C_Display",
		   A."X_Display",
		   A."L_AppType" AS "C_AppType",
		   A."L_AppType" AS "L_AppType_Key",
		   COALESCE( C."X_Display" ->> %(lang)s, C."X_Display" ->> ( C."X_Display" ->> '' ) ) AS "L_AppType_Display",
		   A."L_Protocol" AS "C_Protocol",
		   A."L_Protocol" AS "L_Protocol_Key",
		   COALESCE( D."X_Display" ->> %(lang)s, D."X_Display" ->> ( D."X_Display" ->> '' ) ) AS "L_Protocol_Display",
		   A."C_IpOrHost",
		   A."C_Port",
		   A."C_Path",
		   A."C_Permission",
		   A."L_Member_Id_Default" AS "L_Member_DefaultId"
	   FROM "A_Application"."T_App" A
	   INNER JOIN "A_AD"."T_Domain" B
		   ON A."L_Domain_Id" = B."C_Id"
	   LEFT OUTER JOIN "A_Const"."W_KeyValue" C
		   ON A."L_AppType"   = C."C_Key"
	   LEFT OUTER JOIN "A_Const"."W_KeyValue" D
		   ON A."L_Protocol"  = D."C_Key"
	   WHERE A."C_Id" = %(id)s
	   LIMIT 100
		   ''', {
			'lang': lang,
			'id': app.get('Id')
		}
	)
	db.close()
	dao = MouseChshDao()
	dao.set_model(MouseChshAppModel)
	dao.set_extra_model(MouseChshDomainModel)
	dao.set_extra_model(MouseChshKeyValueModel, key='AppType')
	dao.set_extra_model(MouseChshKeyValueModel, key='Protocol')
	apps = dao.parse(data)
	if len(apps) <= 0:
		return
	return apps[0]
